//这个文件专门处理用户相关
const express = require('express')
const bcryptjs = require('bcryptjs')

const router = express.Router()
//引入数据库相关的model文件
const UserModel = require('../models/user')

//注册
router.post('/api/users', async (req, res) => {
    let username = req.body.username
    let password = req.body.password
    password = await bcryptjs.hash(password, 12)
    const user = new UserModel({
        username,
        password
    })
    await user.save()
    res.send({
        code: 0,
        msg: 'ok'
    })
})
//登录
router.post('/api/login', async (req, res) => {
    let username = req.body.username
    let password = req.body.password

    //先根据用户名去查找用户
    const user = await UserModel.findOne({ username })
    if (!user) {
        res.send({
            code: -1,
            msg: '用户名不存在'
        })
        return
    }
    let isOK = await bcryptjs.compare(password, user.password)
    if (isOK) {
        res.send({
            code: 1,
            msg: 'ok',
            data: {
                userId: user._id,
                username: username
            }
        })
    } else {
        res.send({
            code: -1,
            msg: '密码错误'
        })
    }
})
//   分割线 --------------------------


//用户登录
router.get('/login', async (req, res) => {
    //获取url地址上的redirect参数
    
    let redirect = req.query.redirect
    res.render('login',{redirect})
})
//登录处理
router.post('/loginAction', async (req, res) => {
    let redirect = req.query.redirect;

    let username = req.body.username
    let password = req.body.password
    let isOK = false
    const user = await UserModel.findOne({ username })
    if (user) {
        isOK = await bcryptjs.compare(password, user.password)
    }
    if (isOK) {
        //用户验证通过
        //1.给session上添加一些用户信息
        req.session.userInfo = {
            userId:user._id,
            username:user.username
        }
        res.redirect(redirect)
    } else {
        res.send('用户名或密码不正确')
    }
})
//用户注册
router.get('/register', async (req, res) => {
    res.render('register')
})
//注册处理
router.post('/registerAction', async (req, res) => {
    const user = new UserModel({
        username: req.body.username,

        password: await bcryptjs.hash(req.body.password, 12)
    })
    await user.save()
    res.redirect("/login")
})
module.exports = router